package com.sun.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ThenAcceptExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 创建异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("初始任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "Hello World";
        });

        // thenAccept: 消费结果（无返回值）
        CompletableFuture<Void> acceptFuture = future.thenAccept(result -> {
            System.out.println("thenAccept执行线程: " + Thread.currentThread().getName());
            System.out.println("消费结果: " + result);
        });

        // thenAcceptAsync: 异步消费结果
        CompletableFuture<Void> asyncAcceptFuture = acceptFuture.thenAcceptAsync(v -> {
            System.out.println("thenAcceptAsync执行线程: " + Thread.currentThread().getName());
            System.out.println("异步消费完成");
        });

        // 等待所有任务完成
        asyncAcceptFuture.get();
        System.out.println("主线程结束");
    }
}
